import Multiplex from "multiplex";
import * as msgpack from "@msgpack/msgpack";
import WebsocketStream, { WebSocketDuplex } from "@httptoolkit/websocket-stream";
import { WAChat } from "./chat";

interface ChatAccount {
  phoneNumber?: string;
}

export class WAChatManager extends Multiplex<{ binaryName: true }> {
  public readonly host: string;
  public readonly chats: Array<WAChat> = [];
  public readonly socket: WebSocketDuplex;

  constructor(host: string) {
    super({ binaryName: true });
    this.host = host;
    this.socket = WebsocketStream(this.host, {
      binary: true,
      protocol: "whatsapp",
    });
    this.socket.pipe(this).pipe(this.socket);

    this.socket.on("data", (data) => {
      return;
    });

    this.socket.on("qrcode", (data) => {
      return;
    });

    this.socket.on("end", () => {
      console.log("连接已关闭");
    });
  }

  createChat(account: ChatAccount, callback: any) {
    const metadata = msgpack.encode(account ?? {}, { useBigInt64: true });
    const stream = this.createStream(metadata);
    const chat = new WAChat(stream, callback);
    this.chats.push(chat);
    return chat;
  }

  // 通过索引获取特定的聊天实例
  getChat(index: number): WAChat | undefined {
    return this.chats[index];
  }

  // 发送消息到指定的聊天子流
  sendMessageToChat(index: number, message: string | Buffer) {
    const chat = this.getChat(index);
    if (chat) {
      // chat.sendMessage(message);
    } else {
      throw new Error(`找不到索引为 ${index} 的聊天`);
    }
  }
}
